package com.harassment.interception.ui.fragments.listManagement.blackListFragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.harassment.interception.R;
import com.harassment.interception.base.HIApplication;
import com.harassment.interception.data.databases.HIDBUtil;
import com.harassment.interception.data.databases.HIDatabase;
import com.harassment.interception.data.databases.entities.BlackList;
import com.harassment.interception.ui.fragments.bottomFragment.BottomBar;
import com.harassment.interception.ui.fragments.dialogFragments.ConfirmDialog;
import com.harassment.interception.ui.fragments.dialogFragments.OnNegativeClickListener;
import com.harassment.interception.ui.fragments.dialogFragments.OnPositiveClickListener;
import com.harassment.interception.ui.fragments.listManagement.dialogFragments.AddBlackListDialog;
import com.harassment.interception.ui.fragments.listManagement.dialogFragments.SelectActionDialog;
import com.harassment.interception.ui.fragments.recyclerView.OnItemClickListener;
import com.harassment.interception.ui.fragments.recyclerView.OnItemLongClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

public class BlackListAdapter extends RecyclerView.Adapter<BlackListAdapter.ViewHolder> implements OnItemClickListener, OnItemLongClickListener {
    private static final String TAG = "BlackListAdapter";
    private List<BlackList> mBlackLists;
    private HashMap<Integer, Boolean> mSelectList;
    private BottomBar mBottomBar;
    private boolean mSelectMode;
    private OnItemClickListener mOnItemClickListener;
    private OnItemLongClickListener mOnItemLongClickListener;
    private Fragment mFragment;
    private ConfirmDialog mConfirmDialog;
    private SelectActionDialog mSelectActionDialog;
    private AddBlackListDialog mAddBlackListDialog;

    @SuppressLint("CheckResult")
    public BlackListAdapter(BottomBar bottomBar, Fragment fragment) {
        mFragment = fragment;
        mBottomBar = bottomBar;
        mSelectList = new HashMap<>();
        mConfirmDialog = new ConfirmDialog();
        mSelectActionDialog = new SelectActionDialog();
        mAddBlackListDialog = new AddBlackListDialog();
        mOnItemLongClickListener = this;
        mOnItemClickListener = this;
        mSelectMode = false;
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                mBlackLists = HIDBUtil.getBlackListDao().getAllBlackList();
                selectInit(mBlackLists.size(), false);
                emitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        BlackListAdapter.this.notifyDataSetChanged();
                    }
                });
        mSelectActionDialog.setOnItemClickListener(new com.harassment.interception.ui.fragments.dialogFragments.OnItemClickListener() {
            @Override
            public void onItemClickListener(View v) {
                selectAction(mSelectActionDialog.getDialog(),v);
            }
        });
        mAddBlackListDialog.setOnPositiveClickListener(new OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(DialogInterface dialog, int which) {
                update(mAddBlackListDialog.getDialogView());
                dialog.cancel();
            }
        });
        mAddBlackListDialog.setOnNegativeClickListener(new OnNegativeClickListener() {
            @Override
            public void onNegativeClickListener(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
    }

    private void selectAction(Dialog dialog,View view){
        switch (view.getId()) {
            case R.id.select_update:
                selectUpdate();
                break;
            case R.id.select:
                select();
                break;
        }
        dialog.cancel();
    }

    @SuppressLint("CheckResult")
    private void update(final View view){
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                addBlackList();
                emitter.onComplete();
            }
            private void addBlackList(){
                BlackList blackList = mBlackLists.get(mSelectActionDialog.getItemPosition());
                EditText number = view.findViewById(R.id.input_number);
                if (number.getText().toString().length() == 0) {
                    return;
                }
                EditText remark = view.findViewById(R.id.input_remark);
                RadioButton dark = view.findViewById(R.id.radio_dark);
                RadioButton accurate = view.findViewById(R.id.radio_accurate);
                CheckBox phone = view.findViewById(R.id.not_intercept_phone);
                CheckBox sms = view.findViewById(R.id.not_intercept_sms);

                blackList.setNumber(number.getText().toString());
                blackList.setRemark(remark.getText().toString());
                if (dark.isChecked()) {
                    blackList.setModel(HIDatabase.DARK_MODEL);
                } else if (accurate.isChecked()) {
                    blackList.setModel(HIDatabase.ACCURATE_MODEL);
                }
                blackList.setPhone(phone.isChecked());
                blackList.setSms(sms.isChecked());

                HIDBUtil.getBlackListDao().updateBlackList(blackList);

            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        BlackListAdapter.this.notifyItemChanged(mSelectActionDialog.getItemPosition());
                        Toast.makeText(getFragment().getActivity(),R.string.update_success,Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void selectUpdate(){
        View view = getFragment().getLayoutInflater().inflate(R.layout.dialog_add_black_list, null);
        EditText number = view.findViewById(R.id.input_number);
        EditText remark = view.findViewById(R.id.input_remark);
        RadioButton dark = view.findViewById(R.id.radio_dark);
        RadioButton accurate = view.findViewById(R.id.radio_accurate);
        CheckBox phone = view.findViewById(R.id.not_intercept_phone);
        CheckBox sms = view.findViewById(R.id.not_intercept_sms);

        BlackList blackList = mBlackLists.get(mSelectActionDialog.getItemPosition());
        number.setText(blackList.getNumber());
        remark.setText(blackList.getRemark());
        if (blackList.getModel() == HIDatabase.DARK_MODEL) {
            dark.setChecked(true);
        }else {
            accurate.setChecked(true);
        }
        phone.setChecked(blackList.isPhone());
        sms.setChecked(blackList.isSms());

        mAddBlackListDialog.setView(view);
        mAddBlackListDialog.show(getFragment().getChildFragmentManager(),AddBlackListDialog.TAG);
    }

    private void select(){
        if (mSelectMode) {
            return;
        }
        mSelectMode = true;
        mSelectList.put(mSelectActionDialog.getItemPosition(), true);
        this.notifyDataSetChanged();
        mBottomBar.showOperateView();
        initOperateBarListener();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_black_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        BlackList blackList = mBlackLists.get(position);
        if (blackList.getModel() == HIDatabase.DARK_MODEL) {
            holder.number.setText(blackList.getNumber() + "*");
        } else {
            holder.number.setText(blackList.getNumber());
        }
        holder.remark.setText(blackList.getRemark());
        if (blackList.isPhone()) {
            holder.telephone.setVisibility(View.VISIBLE);
        } else {
            holder.telephone.setVisibility(View.GONE);
        }
        if (blackList.isSms()) {
            holder.sms.setVisibility(View.VISIBLE);
        } else {
            holder.sms.setVisibility(View.GONE);
        }

        if (mSelectMode) {
            holder.select.setVisibility(View.VISIBLE);
            holder.select.setChecked(mSelectList.get(position));
        } else {
            holder.select.setVisibility(View.GONE);
        }

        if (mOnItemClickListener != null) {
            View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.itemView, position);
                }
            };
            holder.phoneItem.setOnClickListener(onClickListener);
            holder.select.setOnClickListener(onClickListener);
        }
        if (mOnItemLongClickListener != null) {
            holder.phoneItem.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int position = holder.getLayoutPosition();
                    return mOnItemLongClickListener.onItemLongClick(holder.itemView, position);
                }
            });
        }

    }

    @Override
    public int getItemCount() {
        return (mBlackLists == null) ? 0 : mBlackLists.size();
    }

    public void selectInit(int length, boolean selectMode) {
        for (int i = 0; i < length; i++) {
            mSelectList.put(i, selectMode);
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        if (!mSelectMode) {
            return;
        }
        if (mSelectList.get(position)) {
            mSelectList.put(position, false);
        } else {
            mSelectList.put(position, true);
        }
        this.notifyItemChanged(position);
    }

    @Override
    public boolean onItemLongClick(View view, int position) {
        mSelectActionDialog.show(getFragment().getChildFragmentManager(),SelectActionDialog.TAG);
        mSelectActionDialog.setItemPosition(position);
        return true;
    }

    private void initOperateBarListener() {
        LinearLayout view = mBottomBar.getOperateView();
        ImageView selectAll = view.findViewById(R.id.select_all);
        ImageView selectClose = view.findViewById(R.id.select_close);
        ImageView selectDelete = view.findViewById(R.id.select_delete);

        selectAll.setOnClickListener(new View.OnClickListener() {
            private boolean selectMode = false;

            @Override
            public void onClick(View v) {
                if (selectMode) {
                    selectInit(mBlackLists.size(), false);
                    selectMode = false;
                } else {
                    selectInit(mBlackLists.size(), true);
                    selectMode = true;
                }
                BlackListAdapter.this.notifyDataSetChanged();
            }
        });
        selectClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelectMode = false;
                mBottomBar.showBottomNavigationView();
                BlackListAdapter.this.notifyDataSetChanged();
                selectInit(mBlackLists.size(), false);
            }
        });
        selectDelete.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View v) {
                mConfirmDialog.setOnPositiveClickListener(new OnPositiveClickListener() {
                    @Override
                    public void onPositiveClickListener(DialogInterface dialog, int which) {
                        delete();
                        dialog.cancel();
                    }
                });
                mConfirmDialog.setOnNegativeClickListener(new OnNegativeClickListener() {
                    @Override
                    public void onNegativeClickListener(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                mConfirmDialog.show(mFragment.getChildFragmentManager(), ConfirmDialog.TAG);
            }
        });
    }

    @SuppressLint("CheckResult")
    private void delete() {
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                Log.d(TAG, "delete: 开始删除");
                deleteItem();
                mSelectMode = false;
                mBlackLists = HIDBUtil.getBlackListDao().getAllBlackList();
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        Log.d(TAG, "run: notifyDataSetChanged");
                        BlackListAdapter.this.notifyDataSetChanged();
                        mBottomBar.showBottomNavigationView();
                        Toast.makeText(HIApplication.getContext(), "已删除！", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void deleteItem() {
        Log.d(TAG, "subscribe: 当前线程：" + Thread.currentThread().getName());
        List<Integer> deleteList = new ArrayList<>();

        for (int i = 0; i < mSelectList.size(); i++) {
            if (mSelectList.get(i)) {
                deleteList.add(i);
                Log.d(TAG, "deleteItem: " + i);
            }
        }

        BlackList[] blackLists = new BlackList[deleteList.size()];
        for (int i = 0; i < deleteList.size(); i++) {
            blackLists[i] = mBlackLists.get(deleteList.get(i));
        }
        HIDBUtil.getBlackListDao().deleteBlackList(blackLists);

        mBlackLists = HIDBUtil.getBlackListDao().getAllBlackList();
        mSelectList = new HashMap<>();
        selectInit(mBlackLists.size(), false);
    }

    public List<BlackList> getBlackLists() {
        return mBlackLists;
    }

    public void setBlackLists(List<BlackList> blackLists) {
        mBlackLists = blackLists;
    }

    public HashMap<Integer, Boolean> getSelectList() {
        return mSelectList;
    }

    public void setSelectList(HashMap<Integer, Boolean> selectList) {
        mSelectList = selectList;
    }

    public BottomBar getBottomBar() {
        return mBottomBar;
    }

    public void setBottomBar(BottomBar bottomBar) {
        mBottomBar = bottomBar;
    }

    public boolean isSelectMode() {
        return mSelectMode;
    }

    public void setSelectMode(boolean selectMode) {
        mSelectMode = selectMode;
    }

    public OnItemClickListener getOnItemClickListener() {
        return mOnItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public OnItemLongClickListener getOnItemLongClickListener() {
        return mOnItemLongClickListener;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        mOnItemLongClickListener = onItemLongClickListener;
    }

    public Fragment getFragment() {
        return mFragment;
    }

    public void setFragment(Fragment fragment) {
        mFragment = fragment;
    }

    public ConfirmDialog getConfirmDialog() {
        return mConfirmDialog;
    }

    public void setConfirmDialog(ConfirmDialog confirmDialog) {
        mConfirmDialog = confirmDialog;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView number;
        TextView remark;
        TextView telephone;
        TextView sms;
        ViewGroup phoneItem;
        CheckBox select;

        public ViewHolder(View itemView) {
            super(itemView);
            phoneItem = itemView.findViewById(R.id.recycler_black_item);
            select = itemView.findViewById(R.id.select);
            number = itemView.findViewById(R.id.number);
            remark = itemView.findViewById(R.id.remark);
            telephone = itemView.findViewById(R.id.telephone);
            sms = itemView.findViewById(R.id.sms);
        }
    }
}
